import type { FormFields } from '../type'
import { ref, watch, nextTick } from 'vue'
import { cloneDeep } from 'lodash-es'

export const useFormData = (formFields: any, props: Record<string, any>) => {
  const _formData = ref<any>({})
  watch(
    () => formFields.value,
    async () => {
      await nextTick()
      // 处理数据缓存问题
      const formData: any = {}
      formFields.value.forEach((field: FormFields) => {
        formData[field.key] = _formData.value[field.key]
      })
      if (formData && typeof formData === 'object') _formData.value = formData
    },
    {
      deep: true,
      immediate: true
    }
  )

  watch(
    () => props.formValue,
    async (val) => {
      await nextTick()
      const _val = cloneDeep(val)
      for (const key of Object.keys(_formData.value)) {
        _formData.value[key] = _val[key]
      }
    },
    {
      deep: true
    }
  )

  return {
    _formData
  }
}
